package com.samoiloff.ui.btns.tab {
	import caurina.transitions.Tweener;

	import flash.display.MovieClip;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.text.TextField;

	/**
	 * @author Damirr
	 */
	public class TabBtnController extends EventDispatcher {
		
		private var _selected: Boolean;
		
		private var _mc:MovieClip;
		private var _hitMc:MovieClip;
		private var _tf:TextField;
		private var _enabled: Boolean;

		
		
		public function TabBtnController(mc: MovieClip, label: String = "Label", bold:Boolean = false) {
			_enabled = true;
			_mc = mc;
			if (mc.hitMc) {
				_hitMc = mc.hitMc;
				_mc.mouseEnabled = false;
			} else {
				_hitMc = _mc;
			}
			_tf = _mc.tf;
//			Fonts.getInstance().applyDefaultFont(_tf, bold);
			
			this.label = label;
			
			_hitMc.useHandCursor = _hitMc.buttonMode = false;
			
			_hitMc.addEventListener(MouseEvent.CLICK, onClick);
		}
		
		public function destroy():void {
			Tweener.removeTweens(_mc);
			_hitMc.removeEventListener(MouseEvent.CLICK, onClick);
			
			_mc = null;
			_hitMc = null;
			_tf = null;
		}

		private function onClick(e:MouseEvent): void {
			dispatchEvent(e);
		}

		
		public function get selected(): Boolean {
			return _selected;
		}
		
		public function set selected(selected: Boolean): void {
			_selected = selected;
			if (_selected) {
				_mc.gotoAndStop(1);
			} else {
				_mc.gotoAndStop(2);
			}
			updateEnabled();
		}

		public function get label(): String {
			return _tf.text;
		}
		
		public function set label(label: String): void {
			_tf.text = label;
		}
		
		public function get enabled(): Boolean {
			return _hitMc.mouseEnabled;
		}
		
		public function set enabled(enabled: Boolean): void {
			_enabled  = enabled;
			updateEnabled();
			Tweener.removeTweens(_mc);
			Tweener.addTween(_mc, {_saturation:_enabled ? 1 : 0, alpha: _enabled ? 1 : .8 });
		}
		
		private function updateEnabled():void {
			_hitMc.mouseEnabled = _enabled && !_selected;
		}
		
		public function get mc():MovieClip {
			return _mc;
		}
		
		public function get tf(): TextField {
			return _tf;
		}
	}
}
